﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ForkCarRelationManager.db;
using ForkCarRelationManager.Business;
using ForkCarRelationManager.Utility;
using System.Text.RegularExpressions;

namespace ForkCarRelationManager
{
    public partial class FormAddMainten : Form
    {
        dbOperate dao=new dbOperate();
        MaintenBI maintenBI = new MaintenBI();
        int type = 0;
        Util util=new Util();
        int RepireID = 0;
        int clientID = 0;
        public FormAddMainten()
        {
            InitializeComponent();
            initForm();
        }
        public FormAddMainten(int RepireID,int clientID,string clientName)
        {
            InitializeComponent();
            initForm();
            TBclient.SelectedValue = clientID;
            this.clientID = clientID;
            this.RepireID = RepireID;
            string ClientName = clientName;
            TBclient.Text = ClientName;
            TBclient.Enabled = false;
            type = 1;
           
        }
      
        public FormAddMainten(String CLientName, int carId)
        {
            InitializeComponent();
            initForm();
            int clientID = maintenBI.getclientIDbyname(CLientName);
            TBclient.SelectedValue = clientID;
            TBclient.Text = CLientName;
            TBdeviceNum.SelectedValue = carId;
            TBdeviceNum_SelectionChangeCommitted(null,null);
            TBclient.Enabled = false;
            TBdeviceNum.Enabled = false;
        }
        private void FormAddMainten_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“forkDatabaseDataSet.UsePartsinfor”中。您可以根据需要移动或删除它。

            
           
        }

     
        private void initForm()
        {
            //刚开始不加载
            //查找所有客户作为数据源
            DataTable clientTable = maintenBI.Getallclient();
            DataRow clientdr = clientTable.NewRow();
            clientdr[0] = "0";
            clientdr[1] = "";
            clientTable.Rows.InsertAt(clientdr, 0);
            TBclient.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //suggest模糊查询,Append自动填充 
            TBclient.AutoCompleteSource = AutoCompleteSource.ListItems;
            this.TBclient.DataSource = clientTable;
            this.TBclient.DisplayMember = "ClientName";//客户所看到的
            this.TBclient.ValueMember = "ID";//标识
          /*  //查找客户有的车
            DataTable carTable = maintenBI.Getcarbycid(TBclient.SelectedValue.ToString());
            DataRow cardr = carTable.NewRow();
            cardr[0] = "0";
            cardr[1] = "";
            carTable.Rows.InsertAt(cardr, 0);
            TBdeviceNum.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //suggest模糊查询,Append自动填充 
            TBdeviceNum.AutoCompleteSource = AutoCompleteSource.ListItems;
            this.TBdeviceNum.DataSource = carTable;
            this.TBdeviceNum.DisplayMember = "DeviceNum";//客户所看到的
            this.TBdeviceNum.ValueMember = "ID";//标识
            */
           /* DataTable maintorTable = maintenBI.Getallmaintor();
            DataRow maintordr = maintorTable.NewRow();
            maintordr[0] = "0";
            maintordr[1] = "";
            maintorTable.Rows.InsertAt(maintordr, 0);
            TBmaintor.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //suggest模糊查询,Append自动填充 
            TBmaintor.AutoCompleteSource = AutoCompleteSource.ListItems;
            this.TBmaintor.DataSource = maintorTable;
            this.TBmaintor.DisplayMember = "MaintorName";//客户所看到的
            this.TBmaintor.ValueMember = "ID";//标识
        */
            
            
        }
       
        /*
         * 添加维修单
         * */
        private void Btn_addmainten_Click(object sender, EventArgs e)
        {
            
            bool ifsubmittext=true;
            int maintain;//必要
            int project=0;//必要
            string clientName = TBclient.Text.Trim();//必要
            string DeviceNum = TBdeviceNum.Text.Trim();//必要
            string maintorName = maintorcheckbox.Text.Trim();//必要
            string proviceNum = TBprovicenum.Text.Trim();//不必要
            string datetime=dateTimePicker1.Text.Replace("年", "/").Replace("月", "/").Replace("日", "").Trim();//必要
            int hour =Convert.ToInt32( hourupdown.Value);//必要
            bool ifmaintanin = radioButton2.Checked;
            if (ifmaintanin)
            {
                maintain = 1;
            }
            else
                maintain = 0;

            if (radioButton3.Checked)
                project = 0;
            else if (radioButton4.Checked)
                project = 1;
            else if (radioButton5.Checked)
                project = 2;
            string symptom = Symptomtext.Text.Trim();//必要
            string maintenContent = maintentext.Text.Trim();//必要
            string clientAdvice = ClientAdvicetext.Text.Trim();//充分不必要
            string backMessage = BackMessagetext.Text.Trim();//充分不必要
            string checkContent = CheckContentText.Text.Trim();//充分不必要
            string changePart = ChangepartText.Text.Trim();//充分不必要
            double fear = 0.00;
            int carId=maintenBI.SearchcarIDbycnum(DeviceNum);
         //   int maintorId=maintenBI.SearchmaintorIDbyname(maintorName);
           
            if (carId == 0&&ifsubmittext)
            {
                ifsubmittext = false;
                MessageBox.Show("不存在该车号");


            }
            else
            {
               /* if (maintorId == 0&&ifsubmittext)
                {
                    ifsubmittext = false;
                    MessageBox.Show("不存在该维修人员");
                }*/
                if (maintorName == "" && ifsubmittext)
                {
                    ifsubmittext = false;
                    MessageBox.Show("不存在该维修人员");
                }
               

            }//判断车号和维修人员是否存在
            if ((clientName == "" || DeviceNum == "" || datetime == "" || symptom == "" || maintenContent == "")&&ifsubmittext)
            {
                ifsubmittext = false;
                MessageBox.Show("名称,设备号,小时数,故障内容,维修内容不能为空");
            }
            //零件部分
             
            int rowcount=dataGridViewX1.RowCount;
            int colmncount = 7;//列数
            List<int> rowexist = new List<int>();
            bool ifsubmitpart=true;
            bool ifpartstand = true;//是否需要提交零件表
           
            for(int i=0;i<rowcount;i++)
            {
                for (int j = 0; j < colmncount; j++)
                {
                    if (dataGridViewX1.Rows[i].Cells[j].Value != null)
                    {
                        if (dataGridViewX1.Rows[i].Cells[j].Value.ToString().Trim() != "" || dataGridViewX1.Rows[i].Cells[j].Value != null)
                        {
                            rowexist.Add(i);
                            break;
                        }
                    }
                }
            }
            if (rowexist.Count!=0)
            {
                ifsubmitpart=true;
            }
            else 
            {
               
                    ifsubmitpart=false;
                
            }
            //判断所填内容是否规范
            if (ifsubmitpart&&ifsubmittext)
            {
                for (int i = 0; i < rowexist.Count; i++)
                {
                    int rowindex=rowexist[i];
                    
                        string PartName=""; 
                        string Standard="";
                        string partCount=""; 

                        string Unit=""; 
                        string UnitPrice=""; 
                        string Price=""; 
                        string Remark="";
                    if(dataGridViewX1.Rows[rowindex].Cells[0].Value!=null)
                    {
                        PartName = dataGridViewX1.Rows[rowindex].Cells[0].Value.ToString();
                    }
                     if (dataGridViewX1.Rows[rowindex].Cells[1].Value != null)
                    {
                         Standard = dataGridViewX1.Rows[rowindex].Cells[1].Value.ToString();//规格可为空
                     }
                     if (dataGridViewX1.Rows[rowindex].Cells[2].Value != null)
                    {
                         partCount = dataGridViewX1.Rows[rowindex].Cells[2].Value.ToString();//数字
                     }
                     if (dataGridViewX1.Rows[rowindex].Cells[3].Value != null)
                    {
                         Unit= dataGridViewX1.Rows[rowindex].Cells[3].Value.ToString();//单位可为空
                     }
                     if (dataGridViewX1.Rows[rowindex].Cells[4].Value != null)
                    {
                         UnitPrice = dataGridViewX1.Rows[rowindex].Cells[4].Value.ToString();//数字
                     }
                    if (dataGridViewX1.Rows[rowindex].Cells[5].Value != null)
                    {
                         Price = dataGridViewX1.Rows[rowindex].Cells[5].Value.ToString();//数字
                     }
                     if (dataGridViewX1.Rows[rowindex].Cells[6].Value != null)
                    {
                         Remark = dataGridViewX1.Rows[rowindex].Cells[6].Value.ToString();//备注能为空;
                     }

                     if (!util.isnumeric(partCount) || !Regex.IsMatch(UnitPrice, @"^[+-]?\d*[.]?\d*$") || !Regex.IsMatch(Price, @"^[+-]?\d*[.]?\d*$") || PartName.Trim() == "" )
                        {
                            MessageBox.Show("名称不能为空，且数量,单价必须为数字");
                            ifpartstand = false;
                            break;
                        }
                      
                }
                    

                    

            }
           
            if (ifsubmittext)//提交维修信息
            {
                int maintenID = maintenBI.addmaintenInfor(carId, datetime, maintain, project, symptom, maintenContent, maintorName, clientAdvice, backMessage, hour, checkContent, changePart, fear, proviceNum, RepireID);
                if (maintenID != 0)
                {
                    bool subcarhour = maintenBI.updatecarSumhour(carId,Convert.ToInt32( SumhourUD.Value));

                    if (ifsubmitpart)//提交所用零件信息
                    {
                        if (ifpartstand)
                        {
                            bool ifok = true;
                            for (int i = 0; i < rowexist.Count; i++)
                            {
                                int rowindex = rowexist[i];
                                string PartName = dataGridViewX1.Rows[rowindex].Cells[0].Value.ToString();
                                string Standard = "";
                                if (dataGridViewX1.Rows[rowindex].Cells[1].Value != null)
                                {
                                    Standard = dataGridViewX1.Rows[rowindex].Cells[1].Value.ToString();//规格可以为空
                                }
                                int partCount = Convert.ToInt32(dataGridViewX1.Rows[rowindex].Cells[2].Value);//数字
                                string Unit = "";
                                if (dataGridViewX1.Rows[rowindex].Cells[3].Value != null)
                                {
                                    Unit = dataGridViewX1.Rows[rowindex].Cells[3].Value.ToString();//单位可以为空
                                }
                                double UnitPrice = Convert.ToDouble(dataGridViewX1.Rows[rowindex].Cells[4].Value);//数字
                                double Price = Convert.ToDouble(dataGridViewX1.Rows[rowindex].Cells[5].Value);//数字
                                string Remark = "";
                                if (dataGridViewX1.Rows[rowindex].Cells[6].Value != null)
                                {
                                    Remark = dataGridViewX1.Rows[rowindex].Cells[6].Value.ToString();//备注能为空
                                }
                                ifok = maintenBI.addmaintenpartInfor(PartName, Standard, partCount, Unit, UnitPrice, Price, Remark, maintenID);

                            }
                            if (!ifok)
                            {

                                maintenBI.deletmaintenbyid(maintenID);

                                MessageBox.Show("维修信息提交失败,原因:维修费用表出错");

                            }
                            else
                            {
                                fear = Convert.ToDouble(pricetext.Text.ToString().Trim());
                                fear = Math.Round(fear, 2);
                              
                                if (maintenBI.updatefearByid(maintenID, fear)&&maintenBI.addworkload(maintorName, fear, hour, maintenID))
                                {

                                    if (type == 1)
                                    {
                                        RepireBI repire = new RepireBI();
                                        repire.updateRepire(RepireID, 1);
 
                                    }
                                    DialogResult dr = MessageBox.Show("添加成功", "提示", MessageBoxButtons.OK);
                                    if (dr == DialogResult.OK)
                                    {

                                        RTform rtform = new RTform(maintain, maintenID);
                                        rtform.Show();
                                    }
                                  //  this.DialogResult = DialogResult.Yes;


                                }
                                else
                                {
                                    MessageBox.Show("总费用提交失败");
                                }
                            }
                        }
                        else
                        {
                            maintenBI.deletmaintenbyid(maintenID);
                            MessageBox.Show("维修信息提交失败");
                        }
                    }
                    else
                    {
                        if (maintenBI.addworkload(maintorName, fear, hour, maintenID))
                        {
                            if (type == 1)
                            {
                                RepireBI repire = new RepireBI();
                                repire.updateRepire(RepireID, 1);

                            }
                            DialogResult dr = MessageBox.Show("添加成功", "提示", MessageBoxButtons.OK);
                            if (dr == DialogResult.OK)
                            {
                               
                                RTform rtform = new RTform(maintain, maintenID);
                                rtform.Show();
                            }
                           // this.DialogResult = DialogResult.Yes;
                         //   MessageBox.Show("添加成功");
                        }
                        else
                            MessageBox.Show("工作量计算错误");
                       
                    }
                    
                }
                else
                    MessageBox.Show("维修信息提交失败");
            
               
            }
            
        }
      
        /*
         * 改变TBlclient
         * */


    /*    private void button3_Click(object sender, EventArgs e)
        {
            string sql = "insert into UsePartsinfor (PartName,Standard,partCount,Unit,UnitPrice,Price,Remark,MaintenId) values  ('1' , '2' , 1 , '1' , 3 , 4 , '5' , 1)";
            bool s = dao.UpdateAndInsert(sql);
        }*/

      
        /*
         * 算金额
         * */

        private void dataGridViewX1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            double sumprice = 0;
            if (dataGridViewX1.Rows[e.RowIndex].Cells[2].Value != null && dataGridViewX1.Rows[e.RowIndex].Cells[4].Value != null)
            {
                string partCount = dataGridViewX1.Rows[e.RowIndex].Cells[2].Value.ToString().Trim();
                string UnitPrice =Convert.ToDouble( dataGridViewX1.Rows[e.RowIndex].Cells[4].Value.ToString().Trim()).ToString("f2");
                dataGridViewX1.Rows[e.RowIndex].Cells[4].Value = UnitPrice;
                if (util.isnumeric(partCount) && (util.isnumeric(UnitPrice) || Regex.IsMatch(UnitPrice, @"^[+-]?\d*[.]?\d*$")))
                {
                    
                    double Price = Convert.ToInt32(partCount) * Convert.ToDouble(UnitPrice);

                    dataGridViewX1.Rows[e.RowIndex].Cells[5].Value = Price.ToString("f2");
                }
            }
            if (dataGridViewX1.Rows.Count != 0)
            {
                for (int rowindex = 0; rowindex < dataGridViewX1.Rows.Count; rowindex++)
                {

                    if (dataGridViewX1.Rows[rowindex].Cells[5].Value != null)
                    {
                        double price = 0.0;
                        if (Regex.IsMatch(dataGridViewX1.Rows[rowindex].Cells[5].Value.ToString(), @"^[+-]?\d*[.]?\d*$"))
                        {
                            price = Convert.ToDouble(dataGridViewX1.Rows[rowindex].Cells[5].Value.ToString());
                        }
                        sumprice += price;
                    }
                }
            }
            pricetext.Text = sumprice.ToString("f2");
        }
        /*
         * TBclienttext改变时改变Tbclient数据源
         * */
        private void TBclient_TextChanged(object sender, EventArgs e)
        {
            /*
            DataTable clientTable=null;
            if (maintenBI.SearchclientIDbyname(TBclient.Text.Trim()) != null)
            {
                clientTable = maintenBI.SearchclientIDbyname(TBclient.Text.Trim());
                TBclient.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //suggest模糊查询,Append自动填充 
                TBclient.AutoCompleteSource = AutoCompleteSource.ListItems;
                this.TBclient.DataSource = clientTable;
                this.TBclient.DisplayMember = "ClientName";//客户所看到的
                this.TBclient.ValueMember = "ID";//标识
            }*/
        
        
        }

     

        private void FormAddMainten_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = DialogResult.Yes;
        }

        private void TBclient_TextChanged_1(object sender, EventArgs e)
        {

        }
        /*
         * 选择车号后显示信息
         * */
        private void TBdeviceNum_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (TBdeviceNum.SelectedValue.ToString() != "0")
            {
                DataTable carTable = maintenBI.SearchcarbyID(Convert.ToInt32(TBdeviceNum.SelectedValue.ToString().Trim()));
                textBoxX1.Text = carTable.Rows[0]["Brand"].ToString();
                textBoxX2.Text = carTable.Rows[0]["CarType"].ToString();
                textBoxX3.Text = carTable.Rows[0]["Model"].ToString();
                textBoxX4.Text = carTable.Rows[0]["SerialNum"].ToString();
             
            }
            else
            {
                
                textBoxX1.Text = "";
                textBoxX2.Text = "";
                textBoxX3.Text = "";
                textBoxX4.Text = "";
            }
        }
        /*
         * 选择客户改变车和员工
         * */
        private void TBclient_SelectedIndexChanged(object sender, EventArgs e)
        {
          
            maintorcheckbox.Items.Clear();
            if (TBclient.SelectedIndex!=0)
            {
                int scompanyID = maintenBI.Getscompanyidbycid(TBclient.SelectedValue.ToString());
                DataTable maintorTable = maintenBI.Getmaintorbyscid(scompanyID.ToString());
                for (int i = 0; i < maintorTable.Rows.Count; i++)
                {

                    maintorcheckbox.Items.Add(maintorTable.Rows[i]["MaintorName"]);
                }
                DataTable carTable = maintenBI.Getcarbycid(TBclient.SelectedValue.ToString());
                DataRow cardr = carTable.NewRow();
                cardr[0] = "0";
                cardr[1] = "";
                carTable.Rows.InsertAt(cardr, 0);
                //TBdeviceNum.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //suggest模糊查询,Append自动填充 
                TBdeviceNum.AutoCompleteSource = AutoCompleteSource.ListItems;
                this.TBdeviceNum.DataSource = carTable;
                this.TBdeviceNum.DisplayMember = "DeviceNum";//客户所看到的
                this.TBdeviceNum.ValueMember = "ID";//标识
            }
            else
                TBdeviceNum.DataSource = null;

        }

        private void Btnaddcar_Click(object sender, EventArgs e)
        {
             int clientid = maintenBI.getclientIDbyname(TBclient.Text.Trim());
             if (clientid == 0)
             {
                 MessageBox.Show("不存在该客户,请添加该客户再添加车");
             }
            else
             {
            int clientID=Convert.ToInt32( TBclient.SelectedValue.ToString());
            if (clientID != 0)
            {
                FormAddCar addcarform = new FormAddCar(clientID, TBclient.Text);
                addcarform.ShowDialog();
                if (addcarform.DialogResult == DialogResult.Yes)
                {
                    DataTable carTable = maintenBI.Getcarbycid(TBclient.SelectedValue.ToString());
                    DataRow cardr = carTable.NewRow();
                    cardr[0] = "0";
                    cardr[1] = "";
                    carTable.Rows.InsertAt(cardr, 0);
                    //TBdeviceNum.AutoCompleteMode = AutoCompleteMode.SuggestAppend; //suggest模糊查询,Append自动填充 
                    TBdeviceNum.AutoCompleteSource = AutoCompleteSource.ListItems;
                    this.TBdeviceNum.DataSource = carTable;
                    this.TBdeviceNum.DisplayMember = "DeviceNum";//客户所看到的
                    this.TBdeviceNum.ValueMember = "ID";//标识
                }
            }
            }
        }

        private void FormAddMainten_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.DialogResult = DialogResult.Yes;
        }

    


       

       
    }
}
